﻿using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;

namespace HuiZe.education.Common
{
    public class WebApiHelper
    {
        public static Tuple<bool, string> HttpPost(string url, string postDataStr, string baseUrl = "https://admin.jiaodehuiyun.com")//https://d-zhzh.bigchun.com   https://admin.jiaodehuiyun.com
        {
            Tuple<bool, string> result;
            url = baseUrl + url;
            try
            {
                byte[] postBytes = Encoding.GetEncoding("utf-8").GetBytes(postDataStr);
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;//(HttpWebRequest)WebRequest.Create(Url);
                //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request.ProtocolVersion = HttpVersion.Version11;
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
                ServicePointManager.CheckCertificateRevocationList = true;
                ServicePointManager.DefaultConnectionLimit = 100;
                ServicePointManager.Expect100Continue = false;
                request.Method = "POST";
                request.ContentType = "application/json"; //"application/x-www-form-urlencoded";// "multipart/form-data";// "application/json";
                request.ContentLength = postBytes.Length;//Encoding.UTF8.GetByteCount(post_string);
                Stream myRequestStream = request.GetRequestStream();
                myRequestStream.Write(postBytes, 0, postBytes.Length);
                myRequestStream.Close();

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
                Logger.WriteLog("返回数据:" + retString);
                result = Tuple.Create(true, retString);
                return result;
            }
            catch (Exception ex)
            {
                Logger.ErrorLog($"webapi调用失败:{url} - {postDataStr}", ex);
                return Tuple.Create(false, ex.Message);
            }
        }

        public static string HttpPost2(string url, string postDataStr)
        {
            //Tuple<bool, string> result;

            try
            {
                byte[] postBytes = Encoding.GetEncoding("utf-8").GetBytes(postDataStr);
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;//(HttpWebRequest)WebRequest.Create(Url);
                //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request.ProtocolVersion = HttpVersion.Version11;
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
                ServicePointManager.CheckCertificateRevocationList = true;
                ServicePointManager.DefaultConnectionLimit = 100;
                ServicePointManager.Expect100Continue = false;
                request.Method = "POST";
                request.ContentType = "application/json"; //"application/x-www-form-urlencoded";// "multipart/form-data";// "application/json";
                request.ContentLength = postBytes.Length;//Encoding.UTF8.GetByteCount(post_string);
                Stream myRequestStream = request.GetRequestStream();
                myRequestStream.Write(postBytes, 0, postBytes.Length);
                myRequestStream.Close();

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
                Logger.WriteLog("返回数据:" + retString);
                //result = Tuple.Create(true, retString);
                return retString;
            }
            catch (Exception ex)
            {
                Logger.ErrorLog($"webapi调用失败:{url} - {postDataStr}", ex);
                return "";
            }
        }


        /// <summary>
        /// Http方式下载文件
        /// </summary>
        /// <param name="url">http地址</param>
        /// <param name="localfile">本地文件</param>
        /// <returns></returns>
        public static bool Download(string url, string localfile)
        {
            if (!url.Contains("https://d-zhzh.bigchun.com") && !url.Contains("https://admin.jiaodehuiyun.com"))
            {
                url = "https://d-zhzh.bigchun.com" + url;
            }
            bool flag = false;
            long startPosition = 0; // 上次下载的文件起始位置
            FileStream writeStream; // 写入本地文件流对象

            // 判断要下载的文件夹是否存在
            if (File.Exists(localfile))
            {
                try
                {
                    File.Delete(localfile);
                  
                    //writeStream = File.OpenWrite(localfile);             // 存在则打开要下载的文件
                    //startPosition = writeStream.Length;                  // 获取已经下载的长度
                    //writeStream.Seek(startPosition, SeekOrigin.Current); // 本地文件写入位置定位
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                finally
                {
                    writeStream = new FileStream(localfile, FileMode.Create);
                }
            }
            else
            {
                writeStream = new FileStream(localfile, FileMode.Create);// 文件不保存创建一个文件
                //startPosition = 0;
            }

            try
            {
                HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(url);// 打开网络连接
                if (startPosition > 0)
                {
                    myRequest.AddRange((int)startPosition);// 设置Range值,与上面的writeStream.Seek用意相同,是为了定义远程文件读取位置
                }

                Stream readStream = myRequest.GetResponse().GetResponseStream();// 向服务器请求,获得服务器的回应数据流
                byte[] btArray = new byte[512];// 定义一个字节数据,用来向readStream读取内容和向writeStream写入内容
                int contentSize = readStream.Read(btArray, 0, btArray.Length);// 向远程文件读第一次

                while (contentSize > 0)// 如果读取长度大于零则继续读
                {
                    writeStream.Write(btArray, 0, contentSize);// 写入本地文件
                    contentSize = readStream.Read(btArray, 0, btArray.Length);// 继续向远程文件读取
                }

                //关闭流
                writeStream.Close();
                readStream.Close();

                flag = true;        //返回true下载成功
            }
            catch (Exception ex)
            {
                writeStream.Close();
                flag = false;       //返回false下载失败
            }

            return flag;
        }

        public static string HttpUploadFile(string url, string path)
        {
            try
            {
                url = "https://d-zhzh.bigchun.com" + url;
                // 设置参数
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "POST";
                string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
                request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
                byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
                byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
                int pos = path.LastIndexOf("\\");
                string fileName = path.Substring(pos + 1);

                //请求头部信息 
                StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName));
                byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());

                FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
                byte[] bArr = new byte[fs.Length];
                fs.Read(bArr, 0, bArr.Length);
                fs.Close();

                Stream postStream = request.GetRequestStream();
                postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
                postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
                postStream.Write(bArr, 0, bArr.Length);
                postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
                postStream.Close();

                //发送请求并获取相应回应数据
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                Stream instream = response.GetResponseStream();
                StreamReader sr = new StreamReader(instream, Encoding.UTF8);
                //返回结果网页（html）代码
                string content = sr.ReadToEnd();
                return content;
            }
            catch (Exception ex)
            {
                return null;     //返回false下载失败
            }

        }

        public static string HttpUploadFile(string url, string path, Action<long, long> _progress)
        {
            try
            {
                url = "https://d-zhzh.bigchun.com" + url;
                // 设置参数
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "POST";
                string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
                request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
                byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
                byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
                int pos = path.LastIndexOf("\\");
                string fileName = path.Substring(pos + 1);

                //请求头部信息 
                StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName));
                byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());

                //FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
                //byte[] bArr = new byte[fs.Length];
                //fs.Read(bArr, 0, bArr.Length);
                //fs.Close();

                using (var _fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    Stream postStream = request.GetRequestStream();
                    postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
                    postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);

                    int _size_read = 0;
                    long _size_uploaded = 0;
                    int _buffer_size = (int)(_fs.Length / 100);
                    if (_buffer_size < 1) _buffer_size = 1;
                    byte[] _buffers = new byte[_buffer_size];
                    using (var _binary_reader = new BinaryReader(_fs))
                    {
                        while (true)
                        {
                            _size_read = _binary_reader.Read(_buffers, 0, _buffers.Length);
                            if (_size_read <= 0)
                                break;

                            postStream.Write(_buffers, 0, _size_read);
                            _size_uploaded += _size_read;
                            _progress(_fs.Length, _size_uploaded);
                            Thread.Sleep(10);
                        }

                        _binary_reader.Close();
                    }
                    _fs.Close();

                    //postStream.Write(bArr, 0, bArr.Length);
                    postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
                    postStream.Close();
                }

                //发送请求并获取相应回应数据
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                Stream instream = response.GetResponseStream();
                StreamReader sr = new StreamReader(instream, Encoding.UTF8);
                //返回结果网页（html）代码
                string content = sr.ReadToEnd();
                return content;
            }
            catch (Exception ex)
            {
                return null;     //返回false下载失败
            }

        }
    }
}
